<template lang="pug">
  .clearfix
    .form-shebao-title.font-16.font-weight 员工合同信息
    .clearfix.bg-white.pall-20.has-disabled(v-show="isEdit")
      Form.ivu-row(ref="formContract" :model="formContract" :rules="rules" :label-width="240")
        FormItem.form-item.ivu-col(v-for="item, index of formContractItem" :label="item.label + '：'" :key="index" :class="item.style" :prop="item.prop")
          template(v-if="item.type === 'input'")
            .w600
              Input(v-model="formContract[item.model]" :placeholder="item.placeholder" :disabled="item.isDisabled || isOnlyView")
          template(v-if="item.type === 'datePicker'")
            DatePicker(:value="formContract[item.model]" :placeholder="item.placeholder" type="date" :disabled="item.isDisabled || isOnlyView" @on-change="handleChangeDatePicker(item.model, $event)")
          template(v-if="item.type === 'upload'")
            Row
              Col.pl-10(span="3" v-if="!isOnlyView && (!isFromWaitInduction && hasEdit)")
                Upload(@before="handleBeforeUpload" @upload="handleUploadSuccess" :employeeId="formContract.employeeId" :params="params" :row="index" :isCanUpload="true")
                Input.display-none(v-model="formContract[item.model]" :placeholder="item.placeholder")
              Col(span="21")
                //- Tag(v-for="c_item, c_index in item.files" :key="c_item.id" :name="c_item.name" :closable="!isOnlyView" @on-close="handleCloseTag(index, c_index, c_item.id)") {{c_item.name}} {{c_item.id}}
                .download-btn.display-inline-block.mr-10.relative(v-for="c_item, c_index in item.files")
                  //- Button(:class="!isOnlyView ? 'pr-55' : 'pr-30'" size="small" @click="previewImg(c_item.downLoadUrl)") {{c_item.name}}
                  Button(v-if="c_item.houzhui === 'jpg' || c_item.houzhui === 'png' || c_item.houzhui === 'gif'" :class="!isOnlyView ? 'pr-55' : 'pr-30'" size="small" @click="previewImg(c_item.downLoadUrl)") {{c_item.name}}
                  Button.btn-follow-txt(v-else :class="!isOnlyView ? 'pr-55' : 'pr-30'" size="small") {{c_item.name}}
                  Icon.btn-r-download(type="md-download" @click="accessoryDownload(c_item.downLoadUrl)" :class="!isOnlyView ? 'r-25' : 'r-5'")
                  Poptip(
                    v-if="!isOnlyView"
                    confirm
                    title="是否删除该附件"
                    @on-ok="handleCloseTag(index, c_index, c_item.id)"
                    width="200"
                  )
                    Icon.btn-r-close(type="md-close")
      .clearfix.text-center.mt-20.mb-20
        Button.mr-10(type="info" @click="handleSubmit('formContract')" :disabled="!canSave") 保存
        Button(type="info" @click="isEdit = false") 返回员工合同列表

    .clearfix(v-show="!isEdit")
      Table.hasTitle-table.beautiful-table(:columns="thead" :data="tableData" :stripe="true" ref="demoTable")
        .clearfix(slot-scope="{ row, index }" slot="attachment")
          p(v-for="item of row.attachment") {{item.name}}

        .clearfix(slot-scope="{ row, index }" slot="action")
          Button(type="text" size="small" :disabled="isOnlyView" @click="handleEditRow(row)") 编辑
          Button(type="text" size="small" :disabled="isOnlyView" @click="isDeleteModal(row.id)") 删除

      //- 仅展示详情时的按钮
      .clearfix.text-center.mt-20.mb-20(v-if="isOnlyView")
        Button.mr-10(type="info" @click="handlepageUp") 查看上一页
        Button.mr-10(v-if="hasEdit && !isFromWaitInduction" type="info" @click="handleModify") 修改
        Button.mr-10(type="info" @click="handlepageDown") 查看下一页
        //- Button(type="info" ghost @click="goEmployeeBookList()") 返回花名册
        Button(v-if="!isFromRoster" type="info" ghost @click="goEmployeeBookList()") 返回花名册
        Button(v-if="isFromRoster" type="info" ghost @click="goRoster()") 返回员工管理

      //- 新建或修改时的按钮
      .clearfix.text-center.mt-20.mb-20(v-if="!isOnlyView")
        Button.mr-10(type="info" @click="handlepageUp") 上一步
        Button.mr-10(type="info" @click="handleEditRow()") 新增
        //- Button(v-if="tableData.length !== 0" type="info" @click="handlepageDown" :disabled="!isNext && !formContract.employeeId") 下一步
        Button(type="info" @click="handlepageDown") 下一步

    //- 删除员工合同信息
    //- DeleteEmployeeModal(ref="DeleteEmployeeModal" @ok="handleSureDelete" :modalTitle="deleteEmployeeTitle")
    //-图片预览
    Modal(title="附件预览" v-model="isPreviewImgModal" footer-hide)
      img(:src="currentPreviewImg")
</template>

<script>
import config from '@/config'
import { EmployeesApi } from '@/api/Employees.api.js'
import { Common } from '@/utils/common.js'
import Upload from '@/components/upload/upload'
// import DeleteEmployeeModal from './deleteEmployeeModal.vue'
import { hetongThead } from '../EBtableHead.js'
import _cloneDeep from 'clone-deep'
import { EBbase } from '../EBbase.js'
const baseUrl = process.env.NODE_ENV === 'development' ? config.baseUrl.dev : config.baseUrl.pro

export default {
  name: '',

  props: {
    // companyId: {
    //   type: String,
    //   default: ''
    // },
    // companyName: {
    //   type: String,
    //   default: ''
    // },
    // employeeId: {
    //   type: String,
    //   default: ''
    // },
    // isOnlyView: {
    //   type: Boolean,
    //   default: false
    // }
  },

  components: {
    Upload
    // DeleteEmployeeModal
  },

  computed: {
    actionArr () {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code
      })
      return arr
    },

    // 编辑
    hasEdit () {
      return this.actionArr.indexOf('Edit') > -1
    }
  },

  data () {
    return {
      isOnlyView: true,
      thead: _cloneDeep(hetongThead),
      // 合同form
      formContract: {
        employeeId: '', // 员工ID
        companyId: '', // 公司ID
        companyName: '', // 公司名称
        id: '', // 合同ID
        code: '',
        duration: '',
        startDate: '',
        endDate: '',
        remark: '',
        attachment: '',
        attaIds: []
      },
      formContractItem: [
        { type: 'input', label: '合同编号', placeholder: '请输入合同编号', prop: 'code', model: 'code', style: 'ivu-col-span-24' },
        { type: 'input', label: '合同年限', placeholder: '请输入合同年限', prop: 'duration', model: 'duration', style: 'ivu-col-span-24' },
        { type: 'datePicker', label: '劳动合同开始时间', placeholder: '请选择劳动合同开始时间', prop: 'startDate', model: 'startDate', style: 'ivu-col-span-24' },
        { type: 'datePicker', label: '劳动合同结束时间', placeholder: '请选择劳动合同结束时间', prop: 'endDate', model: 'endDate', style: 'ivu-col-span-24' },
        { type: 'upload', label: '附件上传', placeholder: '请上传附件', prop: 'attachment', model: 'attachment', style: 'ivu-col-span-24', files: [] },
        { type: 'input', label: '备注', placeholder: '请输入备注', prop: 'remark', model: 'remark', style: 'ivu-col-span-24' }
      ],
      rules: {
        code: [
          { required: true, message: '请输入合同编号' }
        ],
        duration: [
          { required: true, message: '请输入合同年限' }
        ],
        startDate: [
          { required: true, message: '请选择劳动合同开始时间' }
        ],
        endDate: [
          { required: true, message: '请选择劳动合同结束时间' }
        ],
        // attachment: [
        //   { required: true, message: '请上传附件' }
        // ]
      },
      params: {
        ID: '',
        rowVersion: '',
        categoryname: '员工合同附件',
        atta: ''
      },
      isNext: false,
      isEdit: false,
      tableData: [],
      deleteEmployeeTitle: '是否确认删除该条员工合同信息？',
      selectContractId: '', // 选中要删除的员工合同ID
      isPreviewImgModal: false,
      currentPreviewImg: null,
      canSave: true,
      isFromRoster: null,
      isFromWaitInduction: null
    }
  },

  watch: {
  },

  mounted () {
    // this.formContract.id = this.id
    this.formContract.employeeId = this.$route.query.employeeId
    this.formContract.companyId = this.$route.query.companyId
    this.formContract.companyName = this.$route.query.companyName
    this.isFromRoster = this.$route.query.isFromRoster // 是否从员工管理页面过来
    this.isFromWaitInduction = this.$route.query.isFromWaitInduction // 是否从待入职员工页面过来

    // URL参数有员工ID时，获取员工基本信息
    if (this.formContract.employeeId !== '' && this.formContract.employeeId !== undefined) {
      this.query()
      this.rules = {}
    }

    if (this.$route.query.isCreateNew) { // isCreateNew参数为true时，为新增
      this.isOnlyView = false
    }

    this.isNext = !this.$route.query.isCreateNew || this.$route.query.employeeId
    console.log('员工合同信息this.isNext: ', this.isNext)
  },

  methods: {
    handleSubmit (name) {
      this.canSave = false
      this.$refs[name].validate((valid) => {
        if (valid) {
          console.log('提交表单', this[name])
          EmployeesApi.postContract(this[name]).then(resp => {
            console.log('resp: ', resp)
            if (resp.status === 200 && resp.data.success) {
              this.$Message.success(resp.data.message)
              this.isNext = true
              // this.isEdit = false
              this.query()
              setTimeout(() => {
                this.isEdit = false
              }, 1500)
            } else {
              this.canSave = true
              this.$Message.error({
                content: resp.data.message,
                duration: 10,
                closable: true
              })
            }
          })
        } else {
          this.$Message.warning('输入有误，请返回检查!')
        }
      })
    },

    // 上一步
    handlepageUp () {
      Common.pageUp(this)
    },

    // 下一步
    handlepageDown () {
      Common.pageDown(this)
    },

    // 新建标签
    handleAddTag (index, model) {
      var num = this.formContractItem[index].files.length
      this.formContractItem[index].files.push(num)
      this.formContract[model] = this.formContractItem[index].files
    },

    // 删除标签
    async handleCloseTag (index, c_index, id) {
      let res = await EmployeesApi.deleteEmpAtta({ attaid: id })
      console.log('删除标签: ', res)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.formContractItem[index].files.splice(c_index, 1) // 本地数组删除
        // 把附件数组中的ID传入到formContract.attaId里去，并转成字符串
        var tempArr = []
        this.formContractItem[index].files.map(item => {
          tempArr.push(item.id)
        })
        this.formContract.attaIds = tempArr
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 上传图片
    handleUploadSuccess (res, row) {
      var files = this.formContractItem[row].files
      var modelName = this.formContractItem[row].model
      console.log('files: ', files)
      console.log('modelName: ', modelName)
      if (res.code === 200 && res.success) {
        files.push(res.data)
      } else {
        this.$Message.error({
          content: res.message,
          duration: 10,
          closable: true
        })
      }
      // 把附件数组中的ID传入到formContract.attaId里去，并转成字符串
      var tempArr = []
      files.map(item => {
        tempArr.push(item.id)
        item.downLoadUrl = '/api/Employee/DownloadFile?id=' + item.id
        item.houzhui = (item.name + '').substring((item.name + '').lastIndexOf('.') + 1)
      })
      // this.formContract[modelName] = tempArr.join(',')
      this.formContract.attaIds = tempArr
      // if (tempArr.length) {}
      console.log('form: ', this.formContract)
    },

    handleBeforeUpload (row) {
      console.log(this.params.file)
      this.params.categoryname = this.formContractItem[row].model
    },

    handleUploadToSubmit (res) {
      console.log('res: ', res)
    },

    // 获取单个员工基本信息
    async query () {
      var self = this
      var params = {
        id: this.formContract.employeeId
      }
      let res = await EmployeesApi.getContract(params)
      console.log('单个员工合同信息res: ', res)
      if (res.data.code === 200 && res.data.success) {
        this.tableData = res.data.data
      } else {
        console.log('单个员工合同信息:', res.data.message)
        this.tableData = [] // 无数据
      }
    },

    // 修改
    handleModify () {
      this.isNext = true
      this.canSave = true
      // this.$emit('handleModify', 2)
      this.isOnlyView = false
    },

    // 新增/修改当前条
    handleEditRow (row) {
      this.isEdit = true
      this.canSave = true
      console.log('row: ', row)
      if (row) {
        console.log('编辑')
        this.formContract.id = row.id
        var attaArr = []
        row.attachment.map(atta => {
          attaArr.push(atta.id)
        })

        this.formContract.attaIds = attaArr
        this.formContractItem.map(item => {
          if (item.model === 'attachment') {
            if (row.attachment.length) {
              // item.downLoadUrl = '/api/Employee/DownloadFile?id=' + row.attachment[0].id
              row.attachment.map((c_item, c_index) => {
                console.log('☀', c_item)
                c_item.downLoadUrl = '/api/Employee/DownloadFile?id=' + c_item.id
                c_item.houzhui = (c_item.name + '').substring((c_item.name + '').lastIndexOf('.') + 1)
              })
            }
            item.files = row.attachment
          } else {
            this.formContract[item.model] = row[item.model]
          }
        })
      } else {
        console.log('新增')
        this.formContract.id = ''
        this.formContractItem.map(item => {
          this.formContract[item.model] = ''
          if (item.type === 'upload') {
            item.files = []
          }
        })
        console.log('this.formContract: ', this.formContract)
      }
    },

    // // 删除员工合同信息-显示弹窗
    // handleSureDelete (id) {
    //   this.$refs.DeleteEmployeeModal.isShowDeleteEmployeeModal = true
    //   this.$refs.DeleteEmployeeModal.selectDelId = id
    // },

    // 删除员工合同信息-确认删除
    async handleSureDelete (id) {
      console.log('确认删除', id)
      let res = await EmployeesApi.deleteContract({ id: id })
      console.log('删除员工合同信息: ', res)
      if (res.status === 200 && res.data.success) {
        this.$Message.success(res.data.message)
        this.query()
      } else {
        this.$Message.error({
          content: res.data.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 是否删除前询问
    isDeleteModal (id) {
      this.$Modal.confirm({
        title: '是否确认删除该合同信息',
        onOk: () => {
          this.handleSureDelete(id)
        }
      })
    },

    // 时间控件
    handleChangeDatePicker (model, value) {
      this.formContract[model] = value
    },

    // 普通附件下载
    accessoryDownload (url) {
      console.log('下载url: ', url)
      window.open(url, '_blank')
    },

    // 图片预览
    previewImg (url) {
      console.log(url)
      this.isPreviewImgModal = true
      this.currentPreviewImg = baseUrl + url.replace('/api', '')
    },

    // 返回员工花名册列表
    goEmployeeBookList () {
      EBbase.goEmployeeBookList(this.$router, this.formContract.companyId, this.formContract.companyName)
    },

    // 返回员工管理
    goRoster () {
      EBbase.goRoster(this.$router)
    }
  }
}
</script>

<style lang="less" scope>
</style>
